﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;


namespace MN.Framework.Data
{
    public class Sql
    {
        public enum ConnectionType
        {
            ConnectionString,
            ConnectionName,
            FirstConnection,
        }
        public static bool ExecuteNonQuery(ConnectionType conType, string connection, ref string CommandAndRes)
        {
            var connectionString = "";
            if (conType == ConnectionType.ConnectionName)
            {
                connectionString = System.Configuration.ConfigurationManager.ConnectionStrings[connection].ConnectionString;
            }
            else if (conType == ConnectionType.FirstConnection)
            {
                connectionString = System.Configuration.ConfigurationManager.ConnectionStrings[0].ConnectionString;
            }
            else if (conType == ConnectionType.ConnectionString)
                connectionString = connection;

            var Connection = new SqlConnection(connectionString);
            try
            {
                Connection.Open();
                new SqlCommand(CommandAndRes, Connection).ExecuteNonQuery();
                return true;
            }
            catch (Exception ex)
            {
                CommandAndRes = ex.Message;
                return false;
            }
            finally
            {
                Connection.Close();
            }
        }

        public static object ExecuteScalar(ConnectionType conType, string connection, string CommandAndRes)
        {
            var connectionString = "";
            if (conType == ConnectionType.ConnectionName)
            {
                connectionString = System.Configuration.ConfigurationManager.ConnectionStrings[connection].ConnectionString;
            }
            else if (conType == ConnectionType.FirstConnection)
            {
                connectionString = System.Configuration.ConfigurationManager.ConnectionStrings[0].ConnectionString;
            }
            else if (conType == ConnectionType.ConnectionString)
                connectionString = connection;

            var Connection = new SqlConnection(connectionString);
            try
            {
                Connection.Open();
                return new SqlCommand(CommandAndRes, Connection).ExecuteScalar();
            }
            catch (Exception ex)
            {
                CommandAndRes = ex.Message;
                return null;
            }
            finally
            {
                Connection.Close();
            }
        }
    }
}
